package com.example.controller;

import com.example.service.RedisService;
import com.example.utils.IDUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@RestController
public class TestController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private RedisService redisService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public static final String NUM_LIST = "NUM_LIST";

    /****
     * @param
     * 对Set随机删除一个值并返回的。
     * @return
     **/
    @RequestMapping(value = "getRandom")
    public Integer getRandom() {
        if (!redisTemplate.hasKey(NUM_LIST)) {
            List<Integer> list = IntStream.rangeClosed(0, 100000).boxed().collect(Collectors.toList());
            redisTemplate.opsForSet().add(NUM_LIST, list.toArray());
        }
        return (Integer) redisTemplate.opsForSet().pop(NUM_LIST);
    }

    /***
     * 设置redis缓存
     * @param ttl 缓存时间
     * @return
     */
    @RequestMapping(value = "putByTtl")
    public String putByTtl(int ttl) {
        String id = IDUtils.getId();
        logger.warn("putByTtl id:{}", id);
        redisTemplate.opsForValue().set(id, id, ttl, TimeUnit.SECONDS);
        return id;
    }
}
